package org.samith.web.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.samith.dao.AdminUserDao;
import org.samith.dao.UserDao;
import org.samith.web.helper.AdminUserSessionManager;
import org.samith.web.helper.AuthenticatedUserSession;
import org.samith.web.helper.LoginRequest;
import org.samith.web.helper.OnlineUserSessionManager;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	
	@EJB
	AdminUserDao adminUserDao;
	
	@EJB
	UserDao userDao;
	
	public void init() throws ServletException {
		super.init();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		getServletConfig().getServletContext().
				getRequestDispatcher("/WelcomeUsers/login.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		
		LoginRequest loginRequest = new LoginRequest(login, password);
		OnlineUserSessionManager onlineUser = new OnlineUserSessionManager(userDao);
		AdminUserSessionManager adminUser = new AdminUserSessionManager(adminUserDao);
		onlineUser.setSuccessor(adminUser);
		
		AuthenticatedUserSession userSession = onlineUser.processRequest(loginRequest);
		System.out.println("======== Final Authenticated session is "+userSession);
		
		request.getSession().setAttribute("authenticatedUser", userSession);
		response.sendRedirect("/"+getServletContext().getInitParameter("applicationROOT")+"/home");
	}
}
